<template>
  <div class="container">
    <input type="text" placeholder="请输入城市名称" v-model="inputValue" />
    <div class="city-list-scroll">
      <ul v-if="inputValue.length > 0">
        <li
          v-for="item in list"
          :key="item.adcode"
          @click="goSearch(item.adcode, item.name)"
        >
          {{ item.name }}
        </li>
        <li v-if="list.length == 0">似乎没有找到你查找的城市</li>
      </ul>
    </div>
    <div class="list-comp" v-if="inputValue.length === 0">
      <ListComp />
    </div>
  </div>
</template>
<script setup>
import { ref, watch } from 'vue'
import { getSearch } from '@/api/weather'
import ListComp from './ListComp.vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const inputValue = ref('')
const list = ref([])
// 监听inputValue的变化
watch(inputValue, async () => {
  const res = await getSearch(inputValue.value)
  list.value = res.districts
})
const goSearch = (key, name) => {
  router.push(`/search/${key}?search=${name}`)
}
</script>
<style scoped lang="scss">
$box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
.container {
  ul {
    width: 100%;
    margin-top: 0.5rem;
    cursor: pointer;
    li {
      margin-bottom: 0.5rem;
      background-color: #004e71;
      padding: 0.5rem 1rem;
      box-shadow: $box-shadow;
    }
  }
  input {
    background-color: rgb(0, 102, 138);
    width: 100%;
    padding: 0.5rem 1rem;
    font-size: 16px;
    border: none;
    border-bottom: 1px solid #fff;
    color: #fff;
    &::placeholder {
      color: #9d9dac;
    }
    &:focus {
      outline: 2px solid transparent;
      border-bottom: 1px solid rgb(0, 78, 113);
      box-shadow: $box-shadow;
    }
  }
  .list-comp {
    margin-top: 1rem;
  }
  .city-list-scroll {
    max-height: 300px; /* 大约5个城市的高度 */
    overflow-y: auto; /* 启用垂直滚动 */
    /* 自定义滚动条样式 */
  }
}
</style>
